package com.LocalMarket.LocalMarketClient.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xmlpull.v1.XmlSerializer;

import 	android.content.Context;
import android.util.Log;
import android.util.Xml;

public class ConfigurationController{

	private String serverAddress, serverPort;
	private Context referredActivity;
	private Document configurationFile;
	
	public ConfigurationController(Context linkedActivity){
		this.referredActivity=linkedActivity;
		
		try {
			this.configurationFile = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(this.referredActivity.getFilesDir()+"/serverSettings.conf"));
			this.serverAddress=this.GetInformationFromXML("ServerAddress");
			this.serverPort=this.GetInformationFromXML("ServerPort");
		} catch (Exception e) {
			this.serverAddress="Address";
			this.serverPort="Port";
			Log.v("Pau", e.getMessage());
		}
	}
	
	public String GetServerAddress(){
		return this.serverAddress;
	}
	
	public String GetServerPort(){
		return this.serverPort;
	}
	
	public boolean SetDefaultServer(String defaultServerAddress, String defaultServerPort){
		this.serverAddress=defaultServerAddress;
		this.serverPort=defaultServerPort;
		try {
			SaveConfigurationToXML();
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}
	
	private void SaveConfigurationToXML() throws IllegalArgumentException, IllegalStateException, IOException{
			FileOutputStream configurationFile = this.referredActivity.openFileOutput("serverSettings.conf", Context.MODE_WORLD_READABLE);
			XmlSerializer serializer = Xml.newSerializer();
			serializer.setOutput(configurationFile, "UTF-8");
			serializer.startDocument(null, Boolean.valueOf(true)); 
			serializer.startTag(null, "LocalMarketClientConfiguration"); 
				serializer.startTag(null, "RemoteServerConfiguration");
					serializer.startTag(null, "ServerAddress");
					serializer.text(this.serverAddress);
					serializer.endTag(null, "ServerAddress");
					serializer.startTag(null, "ServerPort");
					serializer.text(this.serverPort);
					serializer.endTag(null, "ServerPort");
				serializer.endTag(null, "RemoteServerConfiguration");
			serializer.endTag(null, "LocalMarketClientConfiguration"); 
			serializer.endDocument();
			serializer.flush();
			configurationFile.close();

	}
	
	private String GetInformationFromXML(String tag){

		return this.configurationFile.getElementsByTagName(tag).item(0).getChildNodes().item(0).getNodeValue();
	}
	
}
